<?php namespace app\api\controller;

use app\common\controller\AuthAndBind;
use think\Controller;
use think\Db;
use alisms\SendSms;
use esign\EsignHandle;

/**
 * api
 */
class User extends AuthAndBind{
	
	public function __construct(){
		parent::__construct();
	}
	
//	public function getUserLevelInfo($userId){
//		$thisDate = date("Y-m-d H:i:s", time());
//		$userInfo = Db::table("gd_user") -> where(['id'=>$userId]) -> find();
//		$levelConfigId = 0;
//		if( $userInfo['level_config_id'] > 0 && $userInfo['level_start_date'] <= $thisDate && $userInfo['level_end_date'] >= $thisDate ){
//			$levelConfigId = $userInfo['level_config_id'];
//		}else{
//			$authGroup = Db::table("gd_auth_group_access") -> alias('a') -> join('gd_auth_group b', 'a.group_id = b.id')  -> field(['b.*']) -> where(['a.uid'=>$userId]) -> find();
//			$levelConfigId = $authGroup['level_config_id'];
//		}
//		return Db::table("gd_level_config") -> where(['id'=>$levelConfigId]) -> find();
//	}

	/**
	 * 获取链接官列表
	 */
	public function getUserLevelState2List(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$date = date("Y-m-d H:i:s", time());

				$where = [];
				$where[] = ['a.is_delete', 'eq', 0];
				$where[] = ['a.level_start_date', 'lt', $date];
				$where[] = ['a.level_end_date', 'gt', $date];
				$where[] = ['b.state', 'eq', 2];
				if( isset($in['referrer_id6']) ) $where[] = ['a.referrer_id6', 'eq', $in['referrer_id6']];
				if( isset($in['referrer_id3']) ) $where[] = ['a.referrer_id3', 'eq', $in['referrer_id3']];
				if( isset($in['referrer_id']) ) $where[] = ['a.referrer_id', 'eq', $in['referrer_id']];
				$data = Db::table("gd_user") -> alias('a')
											 -> join('gd_level_config b', 'a.level_config_id = b.id', 'left')
											 -> field(['a.*']) -> where($where) -> select();
				 
				$count = Db::table("gd_user") -> alias('a')
											 -> join('gd_level_config b', 'a.level_config_id = b.id', 'left')
											 -> where($where) -> count();

				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取链接官列表',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}

	/**
	 * 获取商家账号列表
	 */
	public function getUserType3List(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();

				$where = [];
				$where[] = ['is_delete', 'eq', 0];
				$where[] = ['type', 'eq', 3];
				if( isset($in['referrer_id6']) ) $where[] = ['referrer_id6', 'eq', $in['referrer_id6']];
				if( isset($in['referrer_id3']) ) $where[] = ['referrer_id3', 'eq', $in['referrer_id3']];
				$data = Db::table("gd_user") -> where($where) -> select();
				$count = Db::table("gd_user") -> where($where) -> count();

				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取商家账号列表',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}

	/**
	 * 获取代理商账号列表
	 */
	public function getUserType6List(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();

				$where = [];
				$where[] = ['is_delete', 'eq', 0];
				$where[] = ['type', 'eq', 6];
				if( isset($in['referrer_id6']) ) $where[] = ['referrer_id6', 'eq', $in['referrer_id6']];
				$data = Db::table("gd_user") -> where($where) -> select();
				$count = Db::table("gd_user") -> where($where) -> count();

				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取代理商账号列表',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}

	/**
	 * 获取指定订单退款/分账详情（翻台猫）
	 */
	public function getOrderSeparateAccountsDetails(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'order_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();

				$where = [];
				$where[] = ['order_id', 'eq', $in['order_id']];
				$data = Db::table("gd_reward") -> where($where) -> find();

				$outArr['code'] = '1';
				$outArr['info'] = $data;
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取指定订单退款/分账详情（翻台猫）',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}

	/**
	 * 获取指定用户指定门店下级用户消费列表（翻台猫）
	 */
	public function getUserRecShopJuniorOrderList(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();

				$pageIndex = isset($in['page']) ? $in['page'] : 1;
				$pageSize = isset($in['num']) ? $in['num'] : 20;
				
				$start = $pageIndex ? ($pageIndex - 1) * $pageSize : 0;
				$num = $pageSize;

				$where = [];
				if( isset($in['search_user_id']) ) $where[] = ['order_user_shop_parent_user_id', 'eq', $in['search_user_id']];
				$where[] = ['is_delete', 'eq', 0];
				$where[] = ['status', 'gt', 0];
				if( isset($in['shop_id']) ) $where[] = ['shop_id', 'eq', $in['shop_id']];
				$data = Db::table("gd_order") -> where($where) -> order("id desc") -> limit($start, $num) -> select();
				$count = Db::table("gd_order") -> where($where) -> count();

				if( !empty($data) ){
					foreach ($data as $k => $v) {
						$data[$k]['user_nickname2'] = Db::table("gd_user") -> where(['id'=>$v['create_user_id']]) -> find()['nickname2'];
					}
				}

				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取指定用户指定门店下级用户消费列表（翻台猫）',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}

	/**
	 * 获取用户推荐门店的下级用户（翻台猫）
	 */
	public function getUserRecShopJuniorUser(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'search_user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();

				$pageIndex = isset($in['page']) ? $in['page'] : 1;
				$pageSize = isset($in['num']) ? $in['num'] : 20;
				
				$start = $pageIndex ? (($pageIndex - 1) * $pageSize) : 0;
				$num = $pageSize;

				$where = [];
				$where[] = ['a.parent_user_id', 'eq', $in['search_user_id']];
				if( isset($in['shop_id']) ) $where[] = ['a.shop_id', 'eq', $in['shop_id']];
				$data = Db::table("gd_user_shop_relationship") -> alias('a') -> join('gd_user b', 'a.user_id = b.id') 
															-> field(['b.*']) -> where($where) -> group("b.id") -> limit($start, $num) -> select();
				$count = Db::table("gd_user_shop_relationship") -> alias('a') -> join('gd_user b', 'a.user_id = b.id') 
															-> where($where) -> group("b.id") -> count();

				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取用户推荐门店的下级用户（翻台猫）',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}

	/**
	 * 获取用户店铺统计（翻台猫个人中心统计）
	 */
	public function getUserShopStatistics(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'search_user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$user = Db::table("gd_user") -> where(['id'=>$in['search_user_id']]) -> find();
				
				$data['withdrawal'] = $user['total_income'];		//已提现金额
				$data['rebate'] = $user['rebate'];					//待提现金额
				$data['totalIncome'] = $user['total_income'];		//总收益

				// 邀请人数
				$where = [];
				$where[] = ['parent_user_id', 'eq', $in['search_user_id']];
				$data['inviteUserNums'] = Db::table("gd_user_shop_relationship") -> where($where) -> group("user_id") -> count();

				// 消费人数
				$where = [];
				$where[] = ['order_user_shop_parent_user_id', 'eq', $in['search_user_id']];
				$where[] = ['order_type', 'eq', 9];
				$where[] = ['is_delete', 'eq', 0];
				$where[] = ['status', 'gt', 0];
				$data['shopUserNums'] = Db::table("gd_order") -> where($where) -> group("create_user_id") -> count();

				// 去过的店
				$where = [];
				$where[] = ['create_user_id', 'eq', $in['search_user_id']];
				$where[] = ['status', 'gt', 0];
				$where[] = ['order_type', 'eq', 9];
				$where[] = ['is_delete', 'eq', 0];
				$data['userShopNums'] = Db::table("gd_order") -> where($where) -> group("shop_id") -> count();

				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取用户店铺统计（翻台猫个人中心统计）',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}

	/**
	 * 增加店铺分享记录
	 */
	public function addShopShareRecords(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'shop_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$newData['user_id'] = $in['user_id'];
				$newData['create_date'] = date("Y-m-d H:i:s", time());
				$newData['type'] = 3;
				$newData['parent_id'] = $in['shop_id'];

				$re = Db::table("gd_share") -> insertGetId($newData);
				if( !$re ) returnResults2('-1', '新增失败,请联系管理员');

				
				$outArr['code'] = '1';
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'增加店铺分享记录',
						'business_type'=>1,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}

	/**
	 * 获取用户消费过的店铺
	 */
	public function getUserConsumptionShop(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'search_user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where = [];
				$where[] = ['a.create_user_id', 'eq', $in['search_user_id']];
				$where[] = ['a.status', 'gt', 0];
				$where[] = ['a.order_type', 'eq', 9];
				$where[] = ['a.is_delete', 'eq', 0];
				$data = Db::table("gd_order") -> alias('a') -> join('gd_shop b', 'a.shop_id = b.id') 
															-> field(['b.*']) -> where($where) -> group("b.id") -> select();
														
				$count = Db::table("gd_order") -> alias('a') -> join('gd_shop b', 'a.shop_id = b.id') 
															 -> where($where) -> group("b.id") -> count();

				if( !empty($data) && isset($in['isGetUserShopStatistics']) && $in['isGetUserShopStatistics'] == 1 ){
					// 获取用户在每个商店的统计

					foreach ($data as $k => $v) {
						$data[$k]['shareNums'] = 0;					//分享次数
						$data[$k]['inviteUserNums'] = 0;			//邀请人数
						$data[$k]['shopUserNums'] = 0;				//消费人数
						$data[$k]['thisShopMoney'] = 0;				//自己消费的金额
						$data[$k]['thisShopReturnMoney'] = 0;		//自己消费返还的金额
						$data[$k]['inviteShopMoney'] = 0;			//邀请他人消费的金额

						// 分享次数
						$where = [];
						$where[] = ['user_id', 'eq', $in['search_user_id']];
						$where[] = ['type', 'eq', 3];
						$where[] = ['parent_id', 'eq', $v['id']];
						$data[$k]['shareNums'] = Db::table("gd_share") -> where($where) -> count();

						// 邀请人数
						$where = [];
						$where[] = ['parent_user_id', 'eq', $in['search_user_id']];
						$where[] = ['shop_id', 'eq', $v['id']];
						$data[$k]['inviteUserNums'] = Db::table("gd_user_shop_relationship") -> where($where) -> group("user_id") -> count();

						// 消费人数
						$where = [];
						$where[] = ['order_user_shop_parent_user_id', 'eq', $in['search_user_id']];
						$where[] = ['order_type', 'eq', 9];
						$where[] = ['is_delete', 'eq', 0];
						$where[] = ['status', 'gt', 0];
						$where[] = ['shop_id', 'eq', $v['id']];
						$data[$k]['shopUserNums'] = Db::table("gd_order") -> where($where) -> group("create_user_id") -> count();

						// 自己消费的金额
						$where = [];
						$where[] = ['create_user_id', 'eq', $in['search_user_id']];
						$where[] = ['order_type', 'eq', 9];
						$where[] = ['is_delete', 'eq', 0];
						$where[] = ['status', 'gt', 0];
						$where[] = ['shop_id', 'eq', $v['id']];
						$data[$k]['thisShopMoney'] = Db::table("gd_order") -> where($where) -> sum("total_price");

						// 自己消费返还的金额
						$where = [];
						$where[] = ['create_user_id', 'eq', $in['search_user_id']];
						$where[] = ['order_type', 'eq', 9];
						$where[] = ['is_delete', 'eq', 0];
						$where[] = ['status', 'eq', 5];
						$where[] = ['shop_id', 'eq', $v['id']];
						$data[$k]['thisShopReturnMoney'] = Db::table("gd_order") -> where($where) -> sum("total_price");

						// 消费人数
						$where = [];
						$where[] = ['order_user_shop_parent_user_id', 'eq', $in['search_user_id']];
						$where[] = ['order_type', 'eq', 9];
						$where[] = ['is_delete', 'eq', 0];
						$where[] = ['status', 'gt', 0];
						$where[] = ['shop_id', 'eq', $v['id']];
						$data[$k]['inviteShopMoney'] = Db::table("gd_order") -> where($where) -> sum("total_price");

					}
				}
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取用户消费过的店铺',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 后台给用户充值
	 */
	public function adminRecharge(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'recharge_user_id', 'money'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['recharge_user_id']];
				$user = Db::table("gd_user") -> where($where) -> find();
				if( empty($user) ) returnResults(['code'=>'-1', 'msg'=>'操作失败,原数据有误']);
				
				$newData['user_id'] = $user['id'];
				$newData['first_money'] = $user['recharge_balance'];
				$newData['after_money'] = $user['recharge_balance'] + $in['money'];
				$newData['money'] = $in['money'];
				$newData['type'] = 2;
				$newData['state'] = 1;
				$newData['create_user_id'] = $in['user_id'];
				$newData['create_user_name'] = $userInfo['info']['nickname'];
				$newData['create_user_type'] = $userInfo['info']['type'];
				$newData['create_date'] = date("Y-m-d H:i:s", time());
				
				Db::startTrans();
				$re = Db::table("gd_recharge_record") -> insertGetId($newData);
				if( !$re ) {
					Db::rollback();
					returnResults2('-1', '新增失败,请联系管理员');
				}
				
				$re = Db::table("gd_user") -> where(['id'=>$newData['user_id']]) -> setInc('recharge_balance', $newData['money']);
				if( !$re ) {
					Db::rollback();
					returnResults2('-1', '新增失败,请联系管理员');
				}
				Db::commit();
				
				$outArr['code'] = '1';
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'后台给用户充值',
						'business_type'=>1,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 获取不限制的小程序码
	 */
	public function createWechatQrcode(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'scene', 'page'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$param['scene'] = $in['scene'];
				$param['page'] = $in['page'];
				$data = controller("service/Wechat") -> createQrcode($param);
				
				if( isset($in['shop_id']) && !empty($in['shop_id']) && isset($in['saveShopQrcode']) && $in['saveShopQrcode'] == 1 ){
					$fileName = time().rand(1000,9999).'.png';
					$file = $data['info'];
					$upType = 1;
					$qnRe = controller("service/Qiniu") -> upFile($fileName, $file, $upType);
					if( isset($qnRe[0]['key']) && !empty($qnRe[0]['key']) ){
						$save['shop_qrcode'] = config("QI_NIU")['domain'] . $qnRe[0]['key'];
						$re = Db::table("gd_shop") -> where(['id'=>$in['shop_id']]) -> update($save);
					}
				}
				
				$outArr['code'] = '1';
				$outArr['info'] = base64_encode($data['info']);
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取不限制的小程序码',
						'business_type'=>1,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 批量设置用户等级
	 */
	public function batchSetUserLevel(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id', 'level_config_id', 'level_start_date', 'level_end_date'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$levelConfig = Db::table("gd_level_config") -> where(['id'=>$in['level_config_id']]) -> find();
				if( empty($levelConfig) ) returnResults(['code'=>'-1', 'msg'=>'操作失败,等级数据有误']);
				
				$where[] = ['id', 'in', $in['id']];
				$oldData = Db::table("gd_user") -> where($where) -> select();
				if( empty($oldData) ) returnResults(['code'=>'-1', 'msg'=>'操作失败,原数据有误']);
				
				$save['level_config_id'] = $in['level_config_id'];
				$save['level_start_date'] = $in['level_start_date'];
				$save['level_end_date'] = $in['level_end_date'];
//				$save['state'] = isset($in['state']) ? $in['state'] : 1;
				foreach ($oldData as $k => $v) {
					if( $levelConfig['state'] == 2 && isset($v['referrer_id6']) && $v['referrer_id6'] == 0 ) returnResults(['code'=>'-1', 'msg'=>'操作失败,【'.$v['nickname2'].'】未绑定上级代理']);
					$c = filterArr($save, array_keys($save), $v);
					if( empty($c) ) unset($oldData[$k]);
				}
				
				Db::startTrans();
				if( !empty($oldData) ){
					$res = Db::table("gd_user") -> where($where) -> update($save);
					if( !$res ){
						Db::rollback();
						returnResults2('-1', '编辑失败,请联系管理员');
					}
				}
				Db::commit();
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'批量设置用户等级',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 用户获取订单提示
	 */
    public function getOrderTips(){
    	if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				
				$userInfo = $this -> getUserInfo();
				
				if( isset($in['source']) ) $where[] = ['source', 'in', $in['source']];
				$where[] = ['create_user_id', 'eq', $in['user_id']];
				$where[] = ['status', 'eq', 0];
				$data = Db::table("gd_order") -> where($where) -> count();
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'用户获取订单提示',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
    }
	
	/**
	 * 后台提现审核
	 */
    public function withdraw(){
    	if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'withdraw_id', 'state'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				
				$userInfo = $this -> getUserInfo();
				
				$userModelObj = new \app\model\model\User;
				$withdrawModelObj = new \app\model\model\Withdraw;
				$withdrawRelevanceModelObj = new \app\model\model\WithdrawRelevance;
				$rewardModelObj = new \app\model\model\Reward;
//				$rewardRecordModelObj = new \app\model\model\RewardRecord;
				
				Db::startTrans();
				foreach ($in['withdraw_id'] as $key => $value) {
					
					$where['id'] = $value;
					
	//				提现记录
					$withdraw = Db::table("gd_withdraw") -> where($where) -> find();
					if( empty($withdraw) ) returnResults(['code'=>'-1', 'msg'=>'操作失败,提现数据有误']);
					if( $withdraw['state'] != 0 ) returnResults(['code'=>'-1', 'msg'=>'操作失败,提现数据已审核']);
					
	//				提现奖励关联表
//					$relevance = $withdrawRelevanceModelObj -> where(['withdraw_id'=>$value]) -> select() -> toArray();
					
//					$rewardId = array_column($relevance, 'reward_id');
					
	//				奖励记录
//					$reward = $rewardModelObj -> where([['id', 'in', $rewardId]]) -> select() -> toArray();
					
					$save = [];
					$save['state'] = $in['state'];
					$save['reason'] = isset($in['reason']) ? $in['reason'] : '';
					$save['approval_date'] = date('Y-m-d H:i:s', time());
					$save['approval_user_id'] = $userInfo['info']['id'];
					$save['approval_user_name'] = $userInfo['info']['nickname'];
					
//					变更提现申请
					$re = Db::table("gd_withdraw") -> where($where) -> update($save);
					if( !$re ){
						Db::rollback();
						returnResults(['code'=>'-1', 'msg'=>'操作失败,请联系管理员', 'info'=>'withdraw']);
					}
					
					if( $save['state'] == 1 ) {
//						变更用户余额
						$user = Db::table("gd_user") -> where(['id'=>$withdraw['user_id']]) -> find();
						$re = Db::table("gd_user") -> where(['id'=>$withdraw['user_id']]) -> setDec('freeze', $withdraw['money']);
						if( !$re ){
							Db::rollback();
							returnResults(['code'=>'-1', 'msg'=>'操作失败,请联系管理员', 'info'=>'user']);
						}
						
//						提现到余额
						if( $withdraw['type'] == 2 ){
//							增加充值余额
							$re = Db::table("gd_user") -> where(['id'=>$withdraw['user_id']]) -> setInc('recharge_balance', $withdraw['money']);
							if( !$re ){
								Db::rollback();
								returnResults(['code'=>'-1', 'msg'=>'操作失败,请联系管理员', 'info'=>'user']);
							}
//							增加充值余额记录
							$newData['user_id'] = $user['id'];
							$newData['first_money'] = $user['recharge_balance'];
							$newData['after_money'] = $user['recharge_balance'] + $withdraw['money'];
							$newData['money'] = $withdraw['money'];
							$newData['type'] = 4;
							$newData['state'] = 1;
							$newData['create_user_id'] = $in['user_id'];
							$newData['create_user_name'] = $userInfo['info']['nickname'];
							$newData['create_user_type'] = $userInfo['info']['type'];
							$newData['create_date'] = date("Y-m-d H:i:s", time());
							
							$re = Db::table("gd_recharge_record") -> insertGetId($newData);
							if( !$re ) {
								Db::rollback();
								returnResults2('-1', '新增失败,请联系管理员');
							}
						}
					}
					if( $save['state'] == 2 ){
//						变更用户余额
						$user = Db::table("gd_user") -> where(['id'=>$withdraw['user_id']]) -> find();
						$re = Db::table("gd_user") -> where(['id'=>$withdraw['user_id']]) -> setDec('freeze', $withdraw['money']);
						$re = Db::table("gd_user") -> where(['id'=>$withdraw['user_id']]) -> setInc('rebate', $withdraw['money']);
						if( !$re ){
							Db::rollback();
							returnResults(['code'=>'-1', 'msg'=>'操作失败,请联系管理员', 'info'=>'user']);
						}
					}
					
					
//					变更充值记录
//					foreach ($reward as $k => $v) {
//						$saveReward = [];
//						if( $save['state'] == 1 ){
//							$saveReward['draw_money'] = $v['rewards'];
//							$saveReward['withdrawal_status'] = 1;
//						}
//						if( $save['state'] == 2 ){
//							$saveReward['withdrawal_status'] = 0;
//						}
//						$re = $rewardModelObj -> where(['id'=>$v['id']]) -> update($saveReward);
//						if( !$re ){
//							Db::rollback();
//							returnResults(['code'=>'-1', 'msg'=>'操作失败,请联系管理员', 'info'=>'reward']);
//						}
//					}
				}
				
				Db::commit();
				
				$outArr['code'] = '1';
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'后台提现审核',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
    }
	
	/**
	 * 后台获取提现列表
	 */
    public function adminGetWithdrawList(){
    	if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$withdrawModelObj = new \app\model\model\Withdraw;
				
				$num = isset($in['num']) ? $in['num'] : 20;
				$start = isset($in['page']) && $in['page'] > 0 ? (($in['page'] - 1) * $num) : 0;
				
				$where = [];
				if( isset($in['state']) ) $where['state'] = $in['state'];
				if( isset($in['name']) && !empty($in['name']) ) $where[] = ['b.name', 'like', '%'.trim($in['name']).'%'];
				$field = ['a.*', 'b.phone', 'b.nickname', 'b.nickname2'];
				
				$data = Db::table("gd_withdraw") -> alias('a') -> join('gd_user b', 'a.user_id = b.id', 'left') -> field($field) -> where($where) -> order('a.id desc') -> limit($start, $num) -> select();
				$totalNums = Db::table("gd_withdraw") -> alias('a') -> join('gd_user b', 'a.user_id = b.id', 'left') -> field(['count(id)'=>'countNums']) -> where($where) -> count();
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $totalNums;
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'后台获取提现列表',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
    }
	
	/**
	 * 获取提现列表（分销）
	 */
    public function getWithdrawList(){
    	if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty([], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where = [];
				if( $userInfo['auth_group']['path'] != 'ALL' ) $where[] = ['user_id', 'eq', $userInfo['info']['id']];						//非总平台
				if( isset($in['user_id']) && !empty($in['user_id']) ) $where[] = ['user_id', 'eq', $in['user_id']];
				
				$pageIndex = isset($in['page']) ? $in['page'] : 1;
				$pageSize = isset($in['num']) ? $in['num'] : 20;
				
				$start = $pageIndex ? ($pageIndex - 1) * $pageSize : 0;
				$num = $pageSize;
				
				$data = Db::table("gd_withdraw") -> where($where) -> order('id desc') -> select();
				$count = Db::table("gd_withdraw") -> where($where) -> count();
				
				if( !empty($data) ){
					foreach ($data as $k => $v) {
						switch ($v['state']) {
							case '0': $data[$k]['state_str'] = '待审核'; break;
							case '1': $data[$k]['state_str'] = '已同意'; break;
							case '2': $data[$k]['state_str'] = '已拒绝'; break;
						}
					}
				}
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取提现列表（分销）',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
    }
	
	/**
	 * 申请提现（分销）
	 */
    public function withdrawal(){
    	if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'totalAmount'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				if( $in['totalAmount'] <= 0 ) returnResults(['code'=>'-1', 'msg'=>'可提现金额有误,请联系管理员']);
					
				if( $in['type'] == 1 && (!isset($in['card_no']) || empty($in['card_no'])) ){
					returnResults(['code'=>'-1', 'msg'=>'操作失败,提现到银行卡必须选择具体的银行卡']);
				}
				
				$user = Db::table("gd_user") -> where(['id'=>$in['user_id']]) -> find();
				if( $user['rebate'] < $in['totalAmount'] ) returnResults(['code'=>'-1', 'msg'=>'可提现金额有误,请联系管理员']);
				
//				$where[] = ['withdrawal_status', 'eq', 0];
//				$where[] = ['referrer_id', 'in', $in['user_id']];
//				$where[] = ['rewards', 'gt', 0];
//				$where[] = ['draw_money', 'eq', 0];
//				$data = Db::table("gd_reward") -> where($where) -> select();
//				if( empty($data) ) returnResults(['code'=>'-1', 'msg'=>'提现数据有误']);
				
				$withdrawal_rules = Db::table("gd_withdrawal_rules") -> where(['id'=>2]) -> find();
				
				$newWithdraw['money'] = 0;
				$newWithdraw['state'] = 0;
				$newWithdraw['user_id'] = $in['user_id'];
				$newWithdraw['type'] = isset($in['type']) ? $in['type'] : 1;
				if( isset($in['type']) ){
					$newWithdraw['tax'] = $in['type'] == 1 && !empty($withdrawal_rules) ? $withdrawal_rules['value'] : 0;
				}else{
					$newWithdraw['tax'] = !empty($withdrawal_rules) ? $withdrawal_rules['value'] : 0;
				}
				$newWithdraw['tax_payment'] = 0;
				$newWithdraw['create_date'] = date("Y-m-d H:i:s");
				$newWithdraw['bank_id'] = isset($in['bank_id']) ? $in['bank_id'] : 0;
				$newWithdraw['bank'] = isset($in['bank']) ? $in['bank'] : '';
				$newWithdraw['card_no'] = isset($in['card_no']) ? $in['card_no'] : '';
				$newWithdraw['money'] = $in['totalAmount'];
//				foreach ($data as $key => $value) {
//					if( $value['withdrawal_status'] != 0 ) returnResults(['code'=>'-1', 'msg'=>'提现数据状态有误']);
//					$newWithdraw['money'] = $newWithdraw['money'] + $value['rewards'];
//				}
//				if( strval(floatval($newWithdraw['money'])) != strval(floatval($in['totalAmount'])) ) returnResults(['code'=>'-1', 'message'=>'提现金额有误']);
				$newWithdraw['tax_payment'] = $newWithdraw['money'] * ($newWithdraw['tax'] / 100);		//税额
				
				Db::startTrans();
				
				$re = Db::table("gd_withdraw") -> insertGetId($newWithdraw);
				if( !$re ){
					Db::rollback();
					returnResults(['code'=>'-1', 'msg'=>'提现失败,请联系管理员', 'info'=>'withdraw']);
				}
				
//				提现和返现关联数据
//				$newWithdrawRelevance = [];
//				foreach ($data as $key => $value) {
//					$newWithdrawRelevance[$key]['withdraw_id'] = $re;
//					$newWithdrawRelevance[$key]['reward_id'] = $value['id'];
//					$newWithdrawRelevance[$key]['user_id'] = $in['user_id'];
//				}
//				
//				$res = Db::table("gd_withdraw_relevance") -> insertAll($newWithdrawRelevance);
//				if( !$res ){
//					Db::rollback();
//					returnResults(['code'=>'-1', 'msg'=>'提现失败,请联系管理员', 'info'=>'withdrawRelevance']);
//				}
				
//				返现数据
//				$projectWhere[] = ['id', 'in', array_column($data, 'id')];
//				$rt = Db::table("gd_reward") -> where($projectWhere) -> update(['withdrawal_status'=>'2']);
//				if( !$rt ){
//					Db::rollback();
//					returnResults(['code'=>'-1', 'msg'=>'提现失败,请联系管理员', 'info'=>'reward']);
//				}
				
				$userWhere[] = ['id', 'eq', $user['id']];
				$userSave['rebate'] = $user['rebate'] - $newWithdraw['money'];
				$userSave['freeze'] = $user['freeze'] + $newWithdraw['money'];
				$rts = Db::table("gd_user") -> where($userWhere) -> update($userSave);
				if( !$rts ){
					Db::rollback();
					returnResults(['code'=>'-1', 'msg'=>'提现失败,请联系管理员', 'info'=>'user']);
				}
				Db::commit();
				
				$outArr['code'] = '1';
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'申请提现（分销）',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
    }
	
	/**
	 * 分享（分销）
	 */
    public function addShare(){
    	if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'type', 'parent_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$newData['user_id'] = $in['user_id'];
				$newData['create_date'] = date("Y-m-d H:i:s", time());
				$newData['type'] = $in['type'];
				$newData['parent_id'] = $in['parent_id'];
				
				Db::startTrans();
				
				$re = Db::table("gd_share") -> insertGetId($newData);
				if( !$re ){
					Db::rollback();
					returnResults(['code'=>-1, 'msg'=>'操作失败,请联系管理员']);
				}
				
//				if( $newData['type'] == 1 ){
//					$noticeModelObj = new \app\model\model\Notice;
//					$re = $noticeModelObj -> where(['id'=>$newData['parent_id']]) -> setInc('share');
//					if( !$re ){
//						Db::rollback();
//						returnResults(['code'=>-1, 'message'=>'操作失败,请联系管理员', 'info'=>'notice']);
//					}
//				}
//				if( $newData['type'] == 2 ){
//					$promotionModelObj = new \app\model\model\Promotion;
//					$re = $promotionModelObj -> where(['id'=>$newData['parent_id']]) -> setInc('share');
//					if( !$re ){
//						Db::rollback();
//						returnResults(['code'=>'-1', 'message'=>'操作失败,请联系管理员', 'info'=>'promotion']);
//					}
//				}
				
				$re = Db::table("gd_user") -> where(['id'=>$in['user_id']]) -> setInc('share');
				if( !$re ){
					Db::rollback();
					returnResults(['code'=>'-1', 'msg'=>'操作失败,请联系管理员', 'info'=>'user']);
				}
				
				Db::commit();
				
				$outArr['code'] = '1';
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'分享（分销）',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
    }
	
	/**
	 * 编辑用户银行卡（分销）
	 */
    public function editUserBankCard(){
    	if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['id', 'user_id', 'bank', 'card_no'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where['id'] = $in['id'];
				$oldData = Db::table("gd_bank_card") -> where($where) -> find();
				if( empty($oldData) ){
					returnResults(['-1', 'message'=>'原数据有误']);
				}
				
				$save['bank'] = isset($in['bank']) && $in['bank'] != $oldData['bank'] ? $in['bank'] : $oldData['bank'];
				$save['card_no'] = isset($in['card_no']) && $in['card_no'] != $oldData['card_no'] ? $in['card_no'] : $oldData['card_no'];
				$save['status'] = isset($in['status']) && $in['status'] != $oldData['status'] ? $in['status'] : $oldData['status'];
				
				$save = filterArr($save, array_keys($save), $oldData);
				if( !empty($save) ){
					$re = Db::table("gd_bank_card") -> where($where) -> update($save);
					if( !$re ){
						returnResults(['code'=>'-1', 'msg'=>'操作失败,请联系管理员']);
					}
				}
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'编辑用户银行卡（分销）',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
    }
	
	/**
	 * 获取用户银行卡列表（分销）
	 */
    public function getUserBankCardList(){
    	if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where['user_id'] = $in['user_id'];
				
				$start = isset($in['page']) ? $in['page'] - 1 : 0;
				$num = isset($in['num']) ? $in['num'] : 20;
				
				$data = Db::table("gd_bank_card") -> where($where) -> order('id desc') -> select();
				$count = Db::table("gd_bank_card") -> where($where) -> count();
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取用户银行卡列表（分销）',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
    }
	
	/**
	 * 添加用户银行卡（分销）
	 */
    public function addUserBankCard(){
    	if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'user_name', 'bank', 'card_no'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$newData['user_id'] = $in['user_id'];
				$newData['user_name'] = $in['user_name'];
				$newData['bank'] = $in['bank'];
				$newData['card_no'] = $in['card_no'];
				$newData['create_date'] = date("Y-m-d H:i:s", time());
				
				$re = Db::table("gd_bank_card") -> insertGetId($newData);
				if( !$re ){
					returnResults(['code'=>'-1', 'msg'=>'操作失败,请联系管理员']);
				}
				
				$outArr['code'] = '1';
				$outArr['info'] = $re;
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'添加用户银行卡（分销）',
						'business_type'=>1,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		
		returnResults($outArr);
    }
	
	/**
	 * 获取累计提成奖励合计（分销）
	 */
    public function getUserCommissionSum(){
    	if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'referrer_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['referrer_id', 'eq', $in['referrer_id']];
				if( isset($in['create_date']) && !empty($in['create_date']) ) $where[] = ['create_date', 'between', $in['create_date']];
				
				$data = Db::table("gd_reward") -> where($where) -> sum("rewards");
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取累计提成奖励合计（分销）',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
    }
	
	/**
	 * 获取被邀请的下级用户下单明细（分销）
	 */
    public function getSubordinateOrderList(){
    	if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty([], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where = [];
				if( $userInfo['auth_group']['path'] != 'ALL' ) $where[] = ['a.referrer_id', 'eq', $userInfo['info']['id']];						//非总平台
				if( isset($in['user_id']) && !empty($in['user_id']) ) $where[] = ['a.referrer_id', 'eq', $in['user_id']];
				if( isset($in['create_order_user_id']) && !empty($in['create_order_user_id']) ) $where[] = ['a.create_order_user_id', 'eq', $in['create_order_user_id']];
				
				$pageIndex = isset($in['page']) ? $in['page'] : 1;
				$pageSize = isset($in['num']) ? $in['num'] : 20;
				
				$start = $pageIndex ? (($pageIndex - 1) * $pageSize) : 0;
				$num = $pageSize;
				
				$data = Db::table("gd_reward") -> alias('a')
								                -> where($where)
												-> order("a.id desc") 
												-> limit($start, $num) 
												-> select();
				$count = Db::table("gd_reward") -> alias('a')
								                -> where($where)
												-> count();
//				$createOrderUserInfo = Db::table("gd_user") -> where(['id'=>$in['create_order_user_id']]) -> find();
				$createOrderUserOrderCount = Db::table("gd_order") -> where([['create_user_id', 'in', array_column($data, 'create_order_user_id')]]) -> sum("num");
				
				if( !empty($data) ){
					foreach ($data as $k => $v) {
						$data[$k]['nickname2'] = Db::table("gd_user") -> where(['id'=>$v['create_order_user_id']]) -> find()['nickname2'];
						
						if( $v['withdrawal_status'] == '-1' ){
							$order = Db::table("gd_order") -> field(['status', 'is_delete', 'check_date']) -> where(['id'=>$v['order_id']]) -> find();
							$data[$k]['withdrawal_status_str'] = '未生效';
							if( $order['is_delete'] == '0' && $order['status'] == '1' ) $data[$k]['withdrawal_status_str'] = calculateRemainingHoursWithBatch($order['check_date']).'小时后生效';
						}else{
							$data[$k]['withdrawal_status_str'] = '已生效';
						}
					}
				}
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;
//				$outArr['createOrderUserInfo'] = $createOrderUserInfo;
				$outArr['createOrderUserOrderCount'] = $createOrderUserOrderCount;
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取被邀请的下级用户下单明细（分销）',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
    }
	
	/**
	 * 获取用户推广层级/邀请成功的用户（分销）
	 */
    public function getPopularizeLevel(){
    	if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where['a.referrer_id'] = $in['user_id'];
				
				$pageIndex = isset($in['page']) ? $in['page'] : 1;
				$pageSize = isset($in['num']) ? $in['num'] : 20;
				
				$start = $pageIndex ? (($pageIndex - 1) * $pageSize) : 0;
				$num = $pageSize;
				$field = ['a.create_order_user_id', 'b.nickname2', 'count(a.id)'=>'totalUserNums', 'sum(a.rewards)'=>'totalRewards', 'sum(a.draw_money)'=>'totalDrawMoney', 'b.avatar'];
				
				$data = Db::table("gd_reward") -> alias('a')
												-> join('gd_user b', 'a.create_order_user_id = b.id', 'left')
												-> field($field)
								                -> where($where)
												-> group('a.create_order_user_id') 
												-> order("a.id desc") 
												-> limit($start, $num) 
												-> select();
				$count = Db::table("gd_reward") -> alias('a')
												-> join('gd_user b', 'a.create_order_user_id = b.id', 'left')
								                -> where($where)
												-> group('a.create_order_user_id') 
												-> count();
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取用户推广层级/邀请成功的用户（分销）',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
    }
	
	/**
	 * 获取会员中心顶部统计（分销）
	 */
	public function getTotalPromotion(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
//				已提现金额
				$data['drawMoney'] = Db::table("gd_reward") -> where(['referrer_id'=>$userInfo['info']['id'], 'withdrawal_status'=>1]) -> sum("rewards");
//				账户充值余额
				$data['recharge_balance'] = $userInfo['info']['recharge_balance'];
//				账户返佣余额
				$data['totalBalance'] = $userInfo['info']['rebate'];
//				累计收益
				$data['totalRewards'] = $userInfo['info']['total_income'];
//				邀请注册人数
				$numberOfRegistrants = Db::table("gd_user") -> where(['referrer_id'=>$userInfo['info']['id'], 'status'=>1]) -> select();
				$data['numberOfRegistrants'] = count($numberOfRegistrants);
//				注册购买人数
				$data['shopUserNums'] = Db::table("gd_order") -> where([['create_user_id', 'in', array_column($numberOfRegistrants, 'id')], ['is_delete', 'eq', 0], ['status', 'not in', [0,4,5,6,7]]]) -> group("create_user_id") -> count();
//				注册购买藏品件数
				$data['shopNums'] = Db::table("gd_order") -> where([['create_user_id', 'in', array_column($numberOfRegistrants, 'id')], ['is_delete', 'eq', 0], ['status', 'not in', [0,4,5,6,7]]]) -> sum("num");
//				分享次数
				$data['shareNums'] = $userInfo['info']['share'];
//				待提现金额（未提现+未生效）
				$data['notTakenAway'] = Db::table("gd_reward") -> where([['referrer_id', 'eq', $userInfo['info']['id']], ['withdrawal_status', 'in', ['-1', 1]]]) -> sum("rewards");
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				
//				写入操作日志
//				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取会员中心顶部统计（分销）',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 减少积分
	 */
	public function decIntegral(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id', 'num'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				if( $in['num'] < 0 || $in['num'] == 0 ) returnResults2('-1', '操作失败,减少积分的数量必须大于0');
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_user") -> where($where) -> lock(true) -> find();
				if( empty($oldData) ) returnResults2('-1', '操作失败,查询用户数据有误');
				if( $oldData['integral'] < $in['num'] ) returnResults2('-1', '操作失败,用户积分余额不足以扣除');
				
				$newData['num'] = $in['num'];
				$newData['type'] = 2;
				$newData['integral_user_id'] = $in['id'];
				$newData['create_user_id'] = $in['user_id'];
				$newData['create_user_name'] = $userInfo['info']['nickname'];
				$newData['create_date'] = date("Y-m-d H:i:s", time());
				
				
				Db::startTrans();
				$re = Db::table("gd_user_integral") -> insertGetId($newData);
				if( !$re ){
					Db::rollback();
					returnResults2('-1', '操作失败,请联系管理员');
				}
				
				$save['integral'] = $oldData['integral'] - $in['num'];
				$re = Db::table("gd_user") -> where($where) -> update($save);
				if( !$re ){
					Db::rollback();
					returnResults2('-1', '操作失败,请联系管理员');
				}
				Db::commit();
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'减少积分',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 增加积分
	 */
	public function incIntegral(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id', 'num'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				if( $in['num'] < 0 || $in['num'] == 0 ) returnResults2('-1', '操作失败,增加积分的数量必须大于0');
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_user") -> where($where) -> lock(true) -> find();
				if( empty($oldData) ) returnResults2('-1', '操作失败,查询用户数据有误');
				
				$newData['num'] = $in['num'];
				$newData['type'] = 1;
				$newData['integral_user_id'] = $in['id'];
				$newData['create_user_id'] = $in['user_id'];
				$newData['create_user_name'] = $userInfo['info']['nickname'];
				$newData['create_date'] = date("Y-m-d H:i:s", time());
				
				
				Db::startTrans();
				$re = Db::table("gd_user_integral") -> insertGetId($newData);
				if( !$re ){
					Db::rollback();
					returnResults2('-1', '操作失败,请联系管理员');
				}
				
				$save['integral'] = $oldData['integral'] + $in['num'];
				$re = Db::table("gd_user") -> where($where) -> update($save);
				if( !$re ){
					Db::rollback();
					returnResults2('-1', '操作失败,请联系管理员');
				}
				Db::commit();
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'增加积分',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 批量删除
	 */
	public function batchDelete(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'in', $in['id']];
				$oldData = Db::table("gd_user") -> where($where) -> select();
				
				if( !empty($oldData) ){
					Db::startTrans();
					foreach ($oldData as $k => $v) {
						if( $v['is_delete'] != 1 ){
							$save['is_delete'] = 1;
							$delRes = Db::table("gd_user") -> where(['id'=>$v['id']]) -> update($save);
							if( !$delRes ) {
								Db::rollback();
								returnResults(['code'=>'-1', 'msg'=>'操作失败,请联系管理员']);
							}
						}
					}
					Db::commit();
				}
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'批量删除用户',
						'business_type'=>2,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 详情
	 */
	public function details(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				$userGroup = $this -> getUserPosition();
				
				$where[] = ['id', 'eq', $in['id']];
				
				$data = Db::table("gd_user") -> where($where) -> find();
				if( !empty($data) ){
					$data['level'] = controller("service/User") -> getUserLevelInfo($data['id']);
					$data['groupName'] = isset($userGroup['info']['name']) ? $userGroup['info']['name'] : '';
				}
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取用户详情',
						'business_type'=>4,
						'oper_name'=> isset($userInfo['info']['nickname']) ? $userInfo['info']['nickname'] : '',
						'oper_user_id'=> isset($userInfo['info']['id']) ? $userInfo['info']['id'] : 0,
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 列表
	 */
	public function index2(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$num = isset($in['num']) ? $in['num'] : 0;
				$start = isset($in['page']) && $in['page'] > 0 ? (($in['page'] - 1) * $num) : 0;
				
				$where = [];
				$where[] = ['is_delete', 'eq', 0];
				if( isset($in['create_date']) ) $where[] = ['create_date', 'between', $in['create_date']];
				if( isset($in['nickname']) ) $where[] = ['nickname', 'like', '%'.trim($in['nickname']).'%'];
				if( isset($in['nickname2']) ) $where[] = ['nickname2', 'like', '%'.trim($in['nickname2']).'%'];
				if( isset($in['phone']) ) $where[] = ['phone', 'like', '%'.trim($in['phone']).'%'];
				if( isset($in['type']) ) $where[] = ['type', 'eq', $in['type']];
				if( isset($in['create_user_id']) ) $where[] = ['create_user_id', 'eq', $in['create_user_id']];
				if( isset($in['status']) ) $where[] = ['status', 'eq', $in['status']];
				if( isset($in['referrer_id']) ) $where[] = ['referrer_id', 'eq', $in['referrer_id']];
				if( isset($in['referrer_id3']) ) $where[] = ['referrer_id3', 'eq', $in['referrer_id3']];
				if( isset($in['referrer_id6']) ) $where[] = ['referrer_id6', 'eq', $in['referrer_id6']];
				if( isset($in['id']) ) $where[] = ['id', 'eq', $in['id']];
				
				$data = Db::table("gd_user") -> where($where) -> order("id desc") -> limit($start, $num) -> select();
				$count = Db::table("gd_user") -> where($where) -> count();
				
				if( !empty($data) ){
					$groupWhere[] = ['a.uid', 'in', array_column($data, 'id')];
					$group = Db::table("gd_auth_group_access") -> alias('a') -> join('gd_auth_group b', 'a.group_id = b.id') -> field(['a.*', 'b.name', 'b.create_date']) -> where($groupWhere) -> select();
					
					$goodsWhere[] = ['create_user_id', 'in', array_column($data, 'id')];
					$goods = Db::table("gd_goods") -> field(['count(id)'=>'countNums', 'create_user_id']) -> where($goodsWhere) -> group("create_user_id") -> select();
					
					$orderWhere[] = ['goods_create_user_id', 'in', array_column($data, 'id')];
					$orderWhere[] = ['status', 'eq', 1];
					$orderWhere[] = ['is_delete', 'eq', 0];
					$order = Db::table("gd_order") -> field(['count(id)'=>'countNums', 'sum(actual_price)'=>'sumActualPrice', 'goods_create_user_id', 'create_user_id']) -> where($orderWhere) -> group("goods_create_user_id,create_user_id") -> select();
//					var_dump(Db::getLastSql());
//					p($order);die;

					$shopWhere[] = ['create_user_id', 'in', array_column($data, 'id')];
					$shop = Db::table("gd_shop") -> where($shopWhere) -> select();
					
					$orderWhere2[] = ['goods_create_user_id', 'in', array_column($data, 'id')];
					$orderWhere2[] = ['status', 'eq', 1];
					$orderWhere2[] = ['is_delete', 'eq', 0];
					$order2 = Db::table("gd_order") -> field(['count(id)'=>'countNums', 'sum(actual_price)'=>'sumActualPrice', 'create_user_id']) -> where($orderWhere2) -> group("create_user_id") -> select();
					
//					推荐人数据
					$referrerNickName = Db::table("gd_user") -> where([['id', 'in', array_column($data, 'referrer_id')]]) -> select();
//					商家数据
					$referrerNickName3 = Db::table("gd_user") -> where([['id', 'in', array_column($data, 'referrer_id3')]]) -> select();
//					代理商数据
					$referrerNickName6 = Db::table("gd_user") -> where([['id', 'in', array_column($data, 'referrer_id6')]]) -> select();
					
					foreach ($data as $k => $v) {
						$data[$k]['group'] = [];
						$data[$k]['goodsNums'] = 0;				//商品数量
						$data[$k]['orderUserNums'] = 0;			//订单购买人数
						$data[$k]['orderActualPrice'] = 0;		//订单实付金额
						$data[$k]['userShopName'] = '';			//用户店铺名称
						$data[$k]['userOrderNums'] = 0;			//用户下单数量
						$data[$k]['userOrderActualPrice'] = 0;	//用户购买金额
						$data[$k]['referrerNickName'] = '';		//推荐人
						$data[$k]['referrerNickName3'] = '';	//商家
						$data[$k]['referrerNickName6'] = '';	//代理商
						
						$data[$k]['level'] = controller("service/User") -> getUserLevelInfo($v['id']);
						$data[$k]['levelName'] = empty($data[$k]['level']) ? '普通用户' : $data[$k]['level']['name'];
						
						if( !empty($group) ){
							foreach ($group as $kk => $vv) {
								if( $v['id'] == $vv['uid'] ) $data[$k]['group'][] = $vv;
							}
						}
						$data[$k]['groupName'] = implode('/', array_column($data[$k]['group'], 'name'));
						if( !empty($goods) ){
							foreach ($goods as $kk => $vv) {
								if( $v['id'] == $vv['create_user_id'] ) $data[$k]['goodsNums'] = $vv['countNums'];
							}
						}
						if( !empty($order) ){
							foreach ($order as $kk => $vv) {
								if( $v['id'] == $vv['goods_create_user_id'] ){
									$data[$k]['orderUserNums'] = $data[$k]['orderUserNums'] + 1;
									$data[$k]['orderActualPrice'] = round($data[$k]['orderActualPrice'] + $vv['sumActualPrice'], 2);
								}
							}
						}
						if( !empty($shop) ){
							foreach ($shop as $kk => $vv) {
								if( $v['id'] == $vv['create_user_id'] ) {
									$data[$k]['userShopName'] = $vv['name'];
									$data[$k]['province'] = $vv['province'];
									$data[$k]['city'] = $vv['city'];
									$data[$k]['area'] = $vv['area'];
								}
							}
						}
						if( !empty($order2) ){
							foreach ($order2 as $kk => $vv) {
								if( $v['id'] == $vv['create_user_id'] ){
									$data[$k]['userOrderNums'] = $vv['countNums'];
									$data[$k]['userOrderActualPrice'] = $vv['sumActualPrice'];
								}
							}
						}
						if( !empty($referrerNickName) ){
							foreach ($referrerNickName as $kk => $vv) {
								if( $v['referrer_id'] == $vv['id'] ) $data[$k]['referrerNickName'] = $vv['nickname2'];
							}
						}
						if( !empty($referrerNickName3) ){
							foreach ($referrerNickName3 as $kk => $vv) {
								if( $v['referrer_id3'] == $vv['id'] ) $data[$k]['referrerNickName3'] = $vv['nickname2'];
							}
						}
						if( !empty($referrerNickName6) ){
							foreach ($referrerNickName6 as $kk => $vv) {
								if( $v['referrer_id6'] == $vv['id'] ) $data[$k]['referrerNickName6'] = $vv['nickname2'];
							}
						}
					}
				}
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;				
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取用户列表2',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}

	/**
	 * 列表
	 */
	public function index(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$num = isset($in['num']) ? $in['num'] : 0;
				$start = isset($in['page']) && $in['page'] > 0 ? (($in['page'] - 1) * $num) : 0;
				
				$where = [];
				$where[] = ['is_delete', 'eq', 0];
				if( isset($userInfo['auth_group']) && $userInfo['auth_group']['path'] == 'STORE' ) $where[] = ['id', 'eq', $userInfo['info']['id']];						//商家
				if( isset($userInfo['auth_group']) && $userInfo['auth_group']['path'] == 'REGION' ) {																		//代理商
					$where2 = [];
					$where2[] = ['is_default', 'eq', 1];
					$where2[] = ['type', 'eq', 1];
					$where2[] = ['province', 'eq', $userInfo['info']['province']];
					$where2[] = ['city', 'eq', $userInfo['info']['city']];
					$where2[] = ['area', 'eq', $userInfo['info']['area']];
					
					$address = Db::table("gd_address") -> where($where2) -> select();
					if( empty($address) ) returnResults(['code'=>'99999']);
					$where[] = ['id', 'in', array_column($address, 'create_user_id')];
				}
				if( isset($in['create_date']) ) $where[] = ['create_date', 'between', $in['create_date']];
				if( isset($in['nickname']) ) $where[] = ['nickname', 'like', '%'.trim($in['nickname']).'%'];
				if( isset($in['nickname2']) ) $where[] = ['nickname2', 'like', '%'.trim($in['nickname2']).'%'];
				if( isset($in['phone']) ) $where[] = ['phone', 'like', '%'.trim($in['phone']).'%'];
				if( isset($in['type']) ) $where[] = ['type', 'eq', $in['type']];
				if( isset($in['create_user_id']) ) $where[] = ['create_user_id', 'eq', $in['create_user_id']];
				if( isset($in['status']) ) $where[] = ['status', 'eq', $in['status']];
				if( isset($in['referrer_id']) ) $where[] = ['referrer_id', 'eq', $in['referrer_id']];
				if( isset($in['id']) ) $where[] = ['id', 'eq', $in['id']];
				
//				获取默认收件地址的用户（代理商下面的用户）
				if( 
					(isset($in['address_province']) && !empty($in['address_province'])) || 
					(isset($in['address_city']) && !empty($in['address_city'])) || 
					(isset($in['address_area']) && !empty($in['address_area'])) 
				 ){
					$where2 = [];
					$where2[] = ['is_default', 'eq', 1];
					$where2[] = ['type', 'eq', 1];
					if( isset($in['address_province']) && !empty($in['address_province']) ) $where2[] = ['province', 'eq', $in['address_province']];
					if( isset($in['address_city']) && !empty($in['address_city']) ) $where2[] = ['city', 'eq', $in['address_city']];
					if( isset($in['address_area']) && !empty($in['address_area']) ) $where2[] = ['area', 'eq', $in['address_area']];
					
					$address = Db::table("gd_address") -> where($where2) -> select();
					if( empty($address) ) returnResults(['code'=>'99999']);
					$where[] = ['id', 'in', array_column($address, 'create_user_id')];
				}
				$data = Db::table("gd_user") -> where($where) -> order("id desc") -> limit($start, $num) -> select();
				$count = Db::table("gd_user") -> where($where) -> count();
				
				if( !empty($data) ){
					$groupWhere[] = ['a.uid', 'in', array_column($data, 'id')];
					$group = Db::table("gd_auth_group_access") -> alias('a') -> join('gd_auth_group b', 'a.group_id = b.id') -> field(['a.*', 'b.name', 'b.create_date']) -> where($groupWhere) -> select();
					
					$goodsWhere[] = ['create_user_id', 'in', array_column($data, 'id')];
					$goods = Db::table("gd_goods") -> field(['count(id)'=>'countNums', 'create_user_id']) -> where($goodsWhere) -> group("create_user_id") -> select();
					
					$orderWhere[] = ['goods_create_user_id', 'in', array_column($data, 'id')];
					$orderWhere[] = ['status', 'eq', 1];
					$orderWhere[] = ['is_delete', 'eq', 0];
					$order = Db::table("gd_order") -> field(['count(id)'=>'countNums', 'sum(actual_price)'=>'sumActualPrice', 'goods_create_user_id', 'create_user_id']) -> where($orderWhere) -> group("goods_create_user_id,create_user_id") -> select();
//					var_dump(Db::getLastSql());
//					p($order);die;

					$shopWhere[] = ['create_user_id', 'in', array_column($data, 'id')];
					$shop = Db::table("gd_shop") -> where($shopWhere) -> select();
					
					$orderWhere2[] = ['goods_create_user_id', 'in', array_column($data, 'id')];
					$orderWhere2[] = ['status', 'eq', 1];
					$orderWhere2[] = ['is_delete', 'eq', 0];
					$order2 = Db::table("gd_order") -> field(['count(id)'=>'countNums', 'sum(actual_price)'=>'sumActualPrice', 'create_user_id']) -> where($orderWhere2) -> group("create_user_id") -> select();
					
					foreach ($data as $k => $v) {
						$data[$k]['group'] = [];
						$data[$k]['goodsNums'] = 0;				//商品数量
						$data[$k]['orderUserNums'] = 0;			//订单购买人数
						$data[$k]['orderActualPrice'] = 0;		//订单实付金额
						$data[$k]['userShopName'] = '';			//用户店铺名称
						$data[$k]['userOrderNums'] = 0;			//用户下单数量
						$data[$k]['userOrderActualPrice'] = 0;	//用户购买金额
						if( !empty($group) ){
							foreach ($group as $kk => $vv) {
								if( $v['id'] == $vv['uid'] ) $data[$k]['group'][] = $vv;
							}
						}
						$data[$k]['groupName'] = implode('/', array_column($data[$k]['group'], 'name'));
						if( !empty($goods) ){
							foreach ($goods as $kk => $vv) {
								if( $v['id'] == $vv['create_user_id'] ) $data[$k]['goodsNums'] = $vv['countNums'];
							}
						}
						if( !empty($order) ){
							foreach ($order as $kk => $vv) {
								if( $v['id'] == $vv['goods_create_user_id'] ){
									$data[$k]['orderUserNums'] = $data[$k]['orderUserNums'] + 1;
									$data[$k]['orderActualPrice'] = round($data[$k]['orderActualPrice'] + $vv['sumActualPrice'], 2);
								}
							}
						}
						if( !empty($shop) ){
							foreach ($shop as $kk => $vv) {
								if( $v['id'] == $vv['create_user_id'] ) {
									$data[$k]['userShopName'] = $vv['name'];
									$data[$k]['province'] = $vv['province'];
									$data[$k]['city'] = $vv['city'];
									$data[$k]['area'] = $vv['area'];
								}
							}
						}
						if( !empty($order2) ){
							foreach ($order2 as $kk => $vv) {
								if( $v['id'] == $vv['create_user_id'] ){
									$data[$k]['userOrderNums'] = $vv['countNums'];
									$data[$k]['userOrderActualPrice'] = $vv['sumActualPrice'];
								}
							}
						}
					}
				}
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;				
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取用户列表',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}

	/**
	 * 编辑用户密码
	 */
	public function editUserPwd(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'password', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where['id'] = $in['id'];
				$oldData = Db::table("gd_user") -> where($where) -> find();
				if( empty($oldData) ) returnResults(['code'=>'-1', 'msg'=>'操作失败,原数据有误']);
				
				$save['password'] = md5( md5( trim($in['password']) ) );
				$save = filterArr($save, array_keys($save), $oldData);
				
				Db::startTrans();
				if( !empty($save) ){
					$newId = Db::table("gd_user") -> where($where) -> update($save);
					if( !$newId ){
						Db::rollback();
						returnResults2('-1', '编辑失败,请联系管理员');
					}
				}
				
				Db::commit();
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'编辑用户密码',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 编辑
	 */
	public function edit(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where['id'] = isset($in['user']['id']) ? $in['user']['id'] : $in['user_id'];
				$oldData = Db::table("gd_user") -> where($where) -> find();
				if( empty($oldData) ) returnResults(['code'=>'-1', 'msg'=>'操作失败,原数据有误']);
				
				$shop = [];
				$saveShop = [];
				if( $oldData['type'] == 3 ){
//					处理商家商店数据
					$shopWhere['create_user_id'] = $oldData['id'];
					$shop = Db::table("gd_shop") -> where($shopWhere) -> find();
					$saveShop['name'] = isset($in['user']['nickname2']) ? $in['user']['nickname2'].'的小店' : $shop['name'];
					$saveShop['status'] = $shop['status'];
					$saveShop['province'] = isset($in['user']['province']) ? $in['user']['province'] : $shop['province'];
					$saveShop['city'] = isset($in['user']['city']) ? $in['user']['city'] : $shop['city'];
					$saveShop['area'] = isset($in['user']['area']) ? $in['user']['area'] : $shop['area'];
					$saveShop['logo'] = isset($in['user']['avatar']) ? json_encode([['name'=>'', 'type'=>'', 'url'=>$in['user']['avatar']]], JSON_UNESCAPED_UNICODE) : $shop['logo'];
					$saveShop = filterArr($saveShop, array_keys($saveShop), $shop);
					
					if( isset($saveShop['province']) || isset($saveShop['city']) || isset($saveShop['area']) ){
						$cW['province'] = isset($saveShop['province']) ? $saveShop['province'] : $shop['province'];
						$cW['city'] = isset($saveShop['city']) ? $saveShop['city'] : $shop['city'];
						$cW['area'] = isset($saveShop['area']) ? $saveShop['area'] : $shop['area'];
						
						$cr = Db::table("gd_shop") -> where($cW) -> find();
						if( !empty($cr) ) returnResults(['code'=>'-1', 'msg'=>'操作失败,该地址已存在']);
					}
				}
				
				$save = [];
				foreach ($in['user'] as $k => $v) {
					if( !in_array($k, ['id', 'user_id']) ){
						if( $k == 'password' ){
							$save[$k] = md5( md5( trim($v) ) );
						}else{
							$save[$k] = $v;
						}
					}
				}
				$save = filterArr($save, array_keys($save), $oldData);
				
				if( isset($save['phone']) ){
//					校验手机号
					$chechPhone = Db::table("gd_user") -> where(['phone'=>$save['phone']]) -> find();
					if( !empty($chechPhone) ) returnResults(['code'=>'-1', 'msg'=>'操作失败,该手机号已存在']);
				}
				
				if( isset($save['type']) && $save['type'] == 3 ){
					$saveShop['create_user_id'] = $oldData['id'];
					$saveShop['name'] = $in['user']['nickname2'].'的小店';
					$saveShop['status'] = 1;
					$saveShop['province'] = isset($in['user']['province']) ? $in['user']['province'] : '';
					$saveShop['city'] = isset($in['user']['city']) ? $in['user']['city'] : '';
					$saveShop['area'] = isset($in['user']['area']) ? $in['user']['area'] : '';
					$saveShop['logo'] = isset($in['user']['avatar']) ? json_encode([['name'=>'', 'type'=>'', 'url'=>$in['user']['avatar']]], JSON_UNESCAPED_UNICODE) : '';
				}
				
				if( isset($save['nickname']) ){
					$check = Db::table("gd_user") -> where(['nickname'=>$save['nickname']]) -> find();
					if( !empty($check) ) returnResults(['code'=>'-1', 'msg'=>'操作失败,该用户名已存在']);
				}
				
				$newAuthGroupAccess = [];
				if( isset($in['authGroupAccess']) && !empty($in['authGroupAccess']) ){
					foreach ($in['authGroupAccess'] as $k => $v) {
						$newAuthGroupAccess[$k]['uid'] = $in['user']['id'];
						$newAuthGroupAccess[$k]['group_id'] = $v;
					}
				}
				$newUserClass = [];
				if( isset($in['classIds']) && !empty($in['classIds']) ){
					foreach ($in['classIds'] as $k => $v) {
						$newUserClass[$k]['user_id'] = $in['user']['id'];
						$newUserClass[$k]['classification_id'] = $v;
					}
				}
				
				Db::startTrans();
				if( !empty($save) ){
					$newId = Db::table("gd_user") -> where($where) -> update($save);
					if( !$newId ){
						Db::rollback();
						returnResults2('-1', '编辑失败,请联系管理员');
					}
				}
				
				if( isset($newAuthGroupAccess) && !empty($newAuthGroupAccess) ){
					$oldAuthGroupAccess = Db::table("gd_auth_group_access") -> where(['uid'=>$in['user']['id']]) -> find();
					if( !empty($oldAuthGroupAccess) ){
						$res = Db::table("gd_auth_group_access") -> where(['uid'=>$in['user']['id']]) -> delete();
						if( !$res ){
							Db::rollback();
							returnResults2('-1', '删除原权限失败,请联系管理员');
						}
					}
					$res = Db::table("gd_auth_group_access") -> insertAll($newAuthGroupAccess);
					if( !$res ){
						Db::rollback();
						returnResults2('-1', '新增权限失败,请联系管理员');
					}
				}
				
				$oldUserClass = Db::table("gd_user_classification") -> where(['user_id'=>$in['user']['id']]) -> find();
				if( !empty($oldUserClass) ){
					$res = Db::table("gd_user_classification") -> where(['user_id'=>$in['user']['id']]) -> delete();
					if( !$res ){
						Db::rollback();
						returnResults2('-1', '删除原用户分类失败,请联系管理员');
					}
				}
				if( isset($newUserClass) && !empty($newUserClass) ){
					$res = Db::table("gd_user_classification") -> insertAll($newAuthGroupAccess);
					if( !$res ){
						Db::rollback();
						returnResults2('-1', '新增用户分类失败,请联系管理员');
					}
				}
				
				if( isset($saveShop) && !empty($saveShop) ){
					if( !empty($shop) ){
						$res = Db::table("gd_shop") -> where($shopWhere) -> update($saveShop);
					}else{
						$saveShop['verify_date'] = date("Y-m-d H:i:s", time());
						$saveShop['verify_content'] = '后台创建商家，自动过审';
						$saveShop['create_user_id'] = $oldData['id'];
						$saveShop['create_user_name'] = $oldData['nickname'];
						$saveShop['create_user_type'] = 3;
						$saveShop['create_date'] = date("Y-m-d H:i:s", time());
						$res = Db::table("gd_shop") -> insertGetId($saveShop);
					}
					if( !$res ){
						Db::rollback();
						returnResults2('-1', '变更用户商店失败,请联系管理员');
					}
				}
				
				Db::commit();
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'编辑用户',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 新增
	 */
	public function add(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$oldData = Db::table("gd_user") -> where(['nickname'=>$in['user']['nickname'], 'is_delete'=>0]) -> find();
				if( !empty($oldData) ) returnResults(['code'=>'-1', 'msg'=>'操作失败,该用户名已存在']);
				
				if( isset($in['user']['type']) && in_array($in['user']['type'], [3,6]) && 
					isset($in['user']['province']) && 
					isset($in['user']['city']) && 
					isset($in['user']['area']) ){
					$checkUserWhere = [];
					$checkUserWhere['type'] = 6;
					$checkUserWhere['province'] = $in['user']['province'];
					$checkUserWhere['city'] = $in['user']['city'];
					$checkUserWhere['area'] = $in['user']['area'];
					$checkUser = Db::table("gd_user") -> where($checkUserWhere) -> find();
					if( !empty($checkUser) ) returnResults(['code'=>'-1', 'msg'=>'操作失败,该省市区已存在代理商']);
				}
				
				$newData = [];
				foreach ($in['user'] as $k => $v) {
					if( !in_array($k, ['id', 'user_id']) ){
						if( $k == 'password' ){
							$newData[$k] = md5( md5( trim($v) ) );
						}else{
							$newData[$k] = $v;
						}
					}
					$newData['create_user_id'] = $in['user_id'];
					$newData['create_user_name'] = $userInfo['info']['nickname'];
					$newData['create_date'] = date("Y-m-d H:i:s", time());
					$newData['logintime'] = '0000-00-00 00:00:00';
				}
				
				Db::startTrans();
				$newId = Db::table("gd_user") -> insertGetId($newData);
				if( !$newId ){
					Db::rollback();
					returnResults2('-1', '新增失败,请联系管理员');
				}
				$re = $newId;
				
				$newAuthGroupAccess = [];
				if( isset($in['authGroupAccess']) && !empty($in['authGroupAccess']) ){
					foreach ($in['authGroupAccess'] as $k => $v) {
						$newAuthGroupAccess[$k]['uid'] = $newId;
						$newAuthGroupAccess[$k]['group_id'] = $v;
					}
					$res = Db::table("gd_auth_group_access") -> insertAll($newAuthGroupAccess);
					if( !$res ){
						Db::rollback();
						returnResults2('-1', '新增失败,请联系管理员');
					}
				}
				
				if( isset($in['classIds']) ){
					$newUserClass = [];
					foreach ($in['classIds'] as $k => $v) {
						$newUserClass[$k]['user_id'] = $newId;
						$newUserClass[$k]['classification_id'] = $v;
					}
					$res = Db::table("gd_user_classification") -> insertAll($newAuthGroupAccess);
					if( !$res ){
						Db::rollback();
						returnResults2('-1', '新增失败,请联系管理员');
					}
				}
				
				if( isset($in['user']['type']) && $in['user']['type'] == 3 ){
//					商家端
					$newShop['name'] = $in['user']['nickname2'].'的小店';
					$newShop['status'] = 1;
					$newShop['verify_date'] = date("Y-m-d H:i:s", time());
					$newShop['verify_content'] = '后台创建商家，自动过审';
					$newShop['create_user_id'] = $newId;
					$newShop['create_user_name'] = $in['user']['nickname'];
					$newShop['create_user_type'] = 3;
					$newShop['create_date'] = date("Y-m-d H:i:s", time());
					$newShop['province'] = isset($in['user']['province']) ? $in['user']['province'] : '';
					$newShop['city'] = isset($in['user']['city']) ? $in['user']['city'] : '';
					$newShop['area'] = isset($in['user']['area']) ? $in['user']['area'] : '';
					$newShop['logo'] = isset($newData['avatar']) ? json_encode([['name'=>'', 'type'=>'', 'url'=>$newData['avatar']]], JSON_UNESCAPED_UNICODE) : '';
//					$newShop['parent_user_id'] = isset($in['user']['referrer_id']) ? $in['user']['referrer_id'] : '0';
					$re = Db::table("gd_shop") -> insertGetId($newShop);
					if( !$re ){
						Db::rollback();
						returnResults2('-1', '新增失败,请联系管理员');
					}
				}
				
				Db::commit();
				
				$outArr['code'] = '1';
				$outArr['info'] = $re;
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'新增用户',
						'business_type'=>1,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
}

?>